const mysql = require('mysql');
const config = require('../libs/default');
const nodemailer = require("nodemailer");
const schedule = require("node-schedule");


// 数据库连接池
var pool = mysql.createPool({
  host: config.database.HOST,
  user: config.database.USERNAME,
  password: config.database.PASSWORD,
  database: config.database.DATABASE,
});


const allUtils = {
  util: {
    msgFormatter(data = {}, msg, status) {
      return {
        data,
        msg,
        status
      }
    },
    ws: {
      isWebSocketOn: false,
      userPool: [],
      msgCache: [],
    }
  },

  // sql语句封装
  query: (sql, values = []) => {
    return new Promise((resolve, reject) => {
      pool.getConnection(function(err, connection) {
        if (err) {
          reject(err)
        } else {
          connection.query(sql, values, (err, rows) => {
            if (err) {
              reject(err)
            } else {
              resolve(rows)
            }
            connection.release()
          })
        }
      })
    })
  },

  // 邮件发送
  mailSend: async(content = ``, subject = `行程提醒 ✔`) => {
    let transporter = nodemailer.createTransport({
      host: "smtp.qq.com",
      port: 465, // SMTP 端口
      secure: true, // true for 465, false for other ports
      auth: {
        user: `1731158132@qq.com`, // qq 邮箱
        pass: `fsbpcwirykhlbffj`, // SMTP 授权码
      },
    });
    await transporter.sendMail({
      from: 'WUDONG-Blog <1731158132@qq.com>', // 发送者的昵称和邮箱地址
      to: "1731158132@qq.com", // 接收者,可写多个接受者
      subject: subject, // 邮件主题
      text: content, // 主体
      // html: 'html', // 可以发送html
    });
  },

  // 删除邮件缓存
  deleteMailCache: (id) => {
    let missionIndex = 0
    let isMissionExist = false
    config.globalInfo.mailCache.map((item, index) => {
      if (item.id == id) {
        item.mission.cancel()
        isMissionExist = true
        missionIndex = index
      }
      return item
    })
    if (isMissionExist) config.globalInfo.mailCache.splice(missionIndex, 1)
  },

  // 新增邮件缓存
  addMailCache: async(id, time, content) => {
    const dataNow = new Date()
    const year = parseInt(time.substring(0, 4))
    const month = parseInt(time.substring(5, 7))
    const day = parseInt(time.substring(8, time.length))
    if (
      // 比当前年份大或相等
      dataNow.getFullYear() <= year &&
      // 比当前月份大或相等
      dataNow.getMonth() + 1 <= month &&
      // 比当前日期大
      dataNow.getDate() < day
    ) {
      // 现在方案: 固定该日的早晨9点提醒用户
      var date = new Date(year, month - 1, day, 9, 0, 0);
      const mailTemp = await schedule.scheduleJob(date, () => {
        // 发送邮件
        allUtils.mailSend(content);
      });
      // 将定时任务加入缓存
      config.globalInfo.mailCache.push({ id: parseInt(id), mission: mailTemp })
    }
  }
}

module.exports = allUtils